import { querychkNum } from "@/api/chkNum";
import useDateList, {
  useDateListRefs
} from "../components/DatePicker/useDateList";
import useWinRes from "./useWinRes";
import { showWarning } from "@/utils/vant";
import { updateParams } from "./useUtils";
interface NumberItem {
  type: keyof NumbersState;
  count: number;
  numbers: string | number;
  showKeyboard: boolean;
}

interface NumbersState {
  numberError: (string | number)[];
  normal: (string | number)[];
  winning: (string | number)[];
  notWinning: (string | number)[];
  suffix_3: (string | number)[];
  prefix_3: (string | number)[];
  suffix_2: (string | number)[];
}

const useNumbers = defineStore("numbers", () => {
  const { toggleWinRes } = useWinRes();
  const { findDrawIdByDate } = useDateList();
  const { curDate } = useDateListRefs();
  const resNumbers = reactive<NumberItem[]>([
    /*{ type: "normal", count: 1, numbers: "", showKeyboard: false },
    { type: "numberError", count: 1, numbers: "123", showKeyboard: false },
    { type: "notWinning", count: 1, numbers: "123", showKeyboard: false },
    { type: "prefix_3", count: 1, numbers: "123456", showKeyboard: false },
    { type: "suffix_3", count: 1, numbers: "123456", showKeyboard: false },
    { type: "suffix_2", count: 1, numbers: "123456", showKeyboard: false },
    { type: "winning", count: 1, numbers: "123", showKeyboard: false }*/
  ]);
  const refreshNumIpt = ref(0);
  const numsParams = reactive<any>({
    draw_id: "",
    numbers: ""
  });

  function sortResNumbers() {
    resNumbers.sort((a: { numbers: any }, b: { numbers: any }) => {
      const numA = a.numbers;
      const numB = b.numbers;
      if (numA === "" && numB === "") return 0;
      if (numA === "") return 1;
      if (numB === "") return -1;
      const minLength = Math.min(numA.length, numB.length);
      for (let i = 0; i < minLength; i++) {
        if (numA[i] !== numB[i]) {
          return numA.charCodeAt(i) - numB.charCodeAt(i);
        }
      }
      return numA.length - numB.length;
    });
    refreshNumIpt.value++;
  }

  function addNumber(nums = "") {
    if (resNumbers.length >= 100) {
      return;
    }
    const existingItem = resNumbers.find(item => item.numbers === nums);
    if (existingItem) {
      existingItem.count += 1;
    } else {
      resNumbers.push({
        type: "normal",
        count: 1,
        numbers: nums,
        showKeyboard: true
      });
    }
  }

  function checkIptNum(array: any[]) {
    let isSend = true;
    isSend = !array.some((item: { numbers: string | any[]; type: string }) => {
      const isNumberInvalid =
        typeof item.numbers === "string" && item.numbers.length < 3;
      if (isNumberInvalid) {
        item.type = "numberError";
        isSend = false;
      }
      return isNumberInvalid;
    });
    if (!array.length) {
      showWarning("请添加需要查询的号码");
      isSend = false;
    }
    return isSend;
  }

  // L6 玩法、N3 玩法
  function setIptNum(array: any[], resData: any[]) {
    array.forEach((item: { numbers: string; type: string }, index: number) => {
      const resItem = resData[index];
      const isWin = !!(resItem.result.length && resItem.msg === "won");
      // 有奖
      if (isWin) {
        resItem?.result?.forEach((it: any) => {
          const level = it.level;
          // 后2
          if (level === "last2") {
            item.type = "suffix_2";
            // 后3
            if (level === "last3b") {
              item.type = "suffix_3";
              // 1等奖 2等奖 3等奖 4等奖 5等奖
              if (
                ["first", "second", "third", "fourth", "fifth"].includes(level)
              ) {
                item.type = "winning";
              }
            }
          }
          // 后3
          if (level === "last3b") {
            item.type = "suffix_3";
            // 1等奖 2等奖 3等奖 4等奖 5等奖
            if (
              ["first", "second", "third", "fourth", "fifth"].includes(level)
            ) {
              item.type = "winning";
            }
          }
          // 前3 + N3 玩法
          if (
            ["last3f"]
              .concat(["straight3", "shuffle3", "straight2", "special"])
              .includes(level)
          ) {
            item.type = "prefix_3";
            // 1等奖 2等奖 3等奖 4等奖 5等奖
            if (
              ["first", "second", "third", "fourth", "fifth"].includes(level)
            ) {
              item.type = "winning";
            }
          }
          // 1等奖 2等奖 3等奖 4等奖 5等奖
          if (["first", "second", "third", "fourth", "fifth"].includes(level)) {
            item.type = "winning";
          }
        });
      } else {
        // 无奖
        item.type = "notWinning";
      }
    });
  }

  async function checkWin(array: any[]) {
    try {
      const draw_id = findDrawIdByDate(curDate.value);
      const numbers = array
        .filter((item: { numbers: string }) => item.numbers !== "")
        .map((item: { numbers: any }) => item.numbers)
        .join(",");
      console.log("处理抽奖逻辑", array, numbers);
      updateParams(
        {
          draw_id,
          numbers
        },
        numsParams
      );
      if (!checkIptNum(array)) {
        refreshNumIpt.value++;
        return;
      }
      const res = await querychkNum(numsParams);
      // console.log(res);
      const resData = res?.data ?? [];
      // 单个号码中奖和未中奖
      if (resData.length === 1 && array.length === 1) {
        const resItem = resData[0];
        const numItem = array[0];
        const isWin = !!(resItem.result.length && resItem.msg === "won");
        setIptNum(array, resData);
        toggleWinRes({
          status: isWin ? "SingleWin" : "SingleLose",
          data: {
            msg: resItem.msg,
            number: resItem.number,
            result: resItem.result,

            count: numItem.count,
            showKeyboard: numItem.showKeyboard,
            type: numItem.type
          }
        });
        return;
      }
      // 多个号码中含有中奖和未中奖
      if (
        resData.length > 1 &&
        array.length > 1 &&
        resData.some((it: any) => it.result.length && it.msg === "won")
      ) {
        setIptNum(array, resData);
        toggleWinRes({
          status: "MultiWin",
          data: {
            resNumbers: array,
            retData: resData
          }
        });
        return;
      }
      // 多个号码全部未中奖
      if (
        resData.length > 1 &&
        array.length > 1 &&
        resData.every((it: any) => !it.result.length && it.msg === "lost")
      ) {
        setIptNum(array, resData);
        toggleWinRes({
          status: "MultiLose",
          data: {
            resNumbers: array,
            retData: resData
          }
        });
        return;
      }
      // 该日期未开奖
      toggleWinRes({
        status: "Pending",
        data: {}
      });
    } catch (error) {
    } finally {
      refreshNumIpt.value++;
    }
  }

  function handleDrawOneByOne() {
    /*console.log(findDrawIdByDate(curDate.value));
    console.log("处理单个号码抽奖逻辑", resNumbers);
    const { toggleWinRes } = useWinRes();
    toggleWinRes({
      status: "SingleWin", // MultiLose(多个未中奖)  MultiWin(多个号码中奖)  Pending(未开奖) SingleLose(单个号码未中奖) SingleWin(单个号码中奖)
      data: {}
    });*/
    checkWin(resNumbers.slice(0, 1));
  }
  function handleCheckAllResults() {
    /*console.log(findDrawIdByDate(curDate.value));
    console.log("处理检查所有结果的逻辑", resNumbers);
    const { toggleWinRes } = useWinRes();
    toggleWinRes({
      status: "Pending", // MultiLose(多个未中奖)  MultiWin(多个号码中奖)  Pending(未开奖) SingleLose(单个号码未中奖) SingleWin(单个号码中奖)
      data: {}
    });*/
    checkWin(resNumbers);
  }
  function handleFocus({ idx }: { idx: number }) {
    console.log(resNumbers, idx);
    resNumbers.forEach((item, index) => {
      if (index !== idx) {
        item.showKeyboard = false;
      }
    });
    resNumbers[idx].showKeyboard = true;
    // 聚焦后回到编辑状态
    resNumbers[idx].type = "normal";
    refreshNumIpt.value++;
  }
  function handleBlur({ idx }: { idx: number }) {
    resNumbers[idx].showKeyboard = false;
  }
  function deleteNumbers({ idx }: { idx: number }) {
    console.log("删除数字", idx, resNumbers);
    resNumbers.splice(idx, 1);
    refreshNumIpt.value++;
  }

  return {
    resNumbers,
    refreshNumIpt,
    sortResNumbers,
    addNumber,
    handleFocus,
    handleBlur,
    deleteNumbers,
    handleCheckAllResults,
    handleDrawOneByOne
  };
});
export const useNumbersRefs = () => {
  const numbersStore = useNumbers();
  return storeToRefs(numbersStore);
};
export default useNumbers;
